from loaddata import modelHDA as db

from analysis import similarity
import numpy as np
from analysis import util
import datetime
# 胜平负分析

# 胜平负-历史数据-数据格式化-页面显示
def getHistoryShowDatas():
    ds = db.getHistoryDataByNearYear(1)
    return ds


# 数据比对，查找相似的历史数据
def getSomeData(typedata,history,sim):
    res = {"typedata":typedata,"somelist":[]}
    somelist = []
    if typedata:
        x1 = np.array(typedata.get("data"))
        for h in history:
            if h.get("data"):
                x2 = np.array(h.get("data"))
                r = similarity.CalSimEuD(x1, x2)
                # 相似度
                if r > sim:
                    somelist.append(h)
        res["somelist"] = somelist
    else:
        res["somelist"] = history
    return res

# 预测(根据统计信息预测)
# 返回：[统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏，预测结果]
def yuchetj(tj,mzl,maxjg,avgjg,variance,crrjg,tv):
    res = [tj,mzl,maxjg,avgjg,variance,crrjg,tv]
    y = 0
    # 预测
    if tj and avgjg:
            # 转化成百分比:当前遗漏/2*平均
            n = crrjg / (variance**(1/2) + avgjg)
            y = round(n,2)
    res.append(y)
    return res


# 统计分析结果(让球胜平负)
def tjanalysisdata(somelist,tp="spf"):
    # {"typedata": typedata, "somelist": []}
    ds = somelist.get("somelist")
    # 分析胜平负
    res = []
    sumres = []

    # 生成一个4行4列的列表
    for i in range(4):
        hang = []
        for j in range(4):
            hang.append([])
        res.append(hang)

    for i in range(4):
        hang = []
        for j in range(4):
            hang.append([])
        sumres.append(hang)

    # 先转化0,1格式，0表示不中，1表示中
    for d in ds:
        #  格式 [结果，陪数，赔率]
        spf_result = d.get("matchResult").get(tp)
        result = util.spfTo012(spf_result[0])  # h胜-0，d平-1，a负-2
        pei = spf_result[1] - 1     # 1赔，2赔，3赔
        pei_v = spf_result[2]   # 赔率

        # 赔数为行，胜平负为列
        for row in range(3):
            # 查找统计赔数和胜平负
            for h in range(3):
                if result == h and pei == row:
                    res[row][h].append(1)
                    sumres[row][h].append(pei_v)
                else:
                    res[row][h].append(0)
                    sumres[row][h].append(0)

    # 统计赔
    for row in range(3):
        ps = []
        qs = []
        for d in ds:
            spf_result = d.get("matchResult").get(tp)
            pei = spf_result[1] - 1
            # 查找统计赔数
            if pei == row:
                ps.append(1)
            else:
                ps.append(0)
            result = util.spfTo012(spf_result[0])  # h胜-0，d平-1，a负-2
            # 查找统计赔数
            if result == row:
                qs.append(1)
            else:
                qs.append(0)
        res[row][3] = ps
        res[3][row] = qs

    for row in range(3):
        cs = []
        for col in range(3):
            cs.append(sum(sumres[row][col]))
        sumres[row][3] = cs
    for row in range(3):
        cs = []
        for col in range(3):
            cs.append(sum(sumres[col][row]))
        sumres[3][row] = cs

    # 统计赔、球
    for i in range(4):
        for j in range(4):
            dlist = res[i][j]
            # 计算遗漏
            mzl,maxjg,avgjg,variance,crrjg = util.tj(dlist)
            # 计算总数
            tj = sum(res[i][j])
            # 计算中奖总赔率
            tv = round(sum(sumres[i][j]),2)
            # 预测根据统计信息 ,返还：[统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏，总赔率，预测结果]
            yr = yuchetj(tj,mzl,maxjg,avgjg,variance,crrjg,tv)
            res[i][j] = yr
    return res

# 显示预测(s:被预测信息，tjds:历史统计数据)
def showyuche(s,tjds,tp="peid_spf"):
    # 保证有被预测信息
    if s:
        qp = []
        peid = s.get(tp)
        # [("s2",3.2),("s3",3.4),....]
        for i in range(len(peid)):
            qiu = util.spfTo012(peid[i][0])
            # (结果，赔)
            qp.append((qiu,i))
        # 使用嵌套的for循环遍历二维数组
        # [统计数量, 命中率, 最大间隔, 平均间隔, 方差, 当前遗漏]

        for i in range(len(tjds)):
            row = tjds[i]
            for j in range(len(row)):
                t = (j,i)
                if t in qp:
                    tjds[i][j].append(1)
                else:
                    tjds[i][j].append(0)

        # [统计数量, 命中率, 最大间隔, 平均间隔, 方差, 当前遗漏,是否是需要预测的数据]
    return tjds

# 单关筛选
def selectSingle(h,single):
    selectList = []
    # 单关筛选
    if single:
        for s in h:
            if single in s.get("singleList"):
                selectList.append(s)
        return selectList
    else:
        return h




# 分析结果（tp="selling"根据正在售卖数据,其他为历史数据）
def analysis(tp,matchId,sim,single):
    if tp == "selling":
        s = db.getSellingData(matchId)
        h = db.getHistoryDataFromYear(2020)
    elif tp == "history":
        s = db.getHistoryDataByMatchID(matchId)
        endDay = s.get("matchDate")
        end_of_year = datetime.datetime.strptime(endDay, '%Y-%m-%d') - datetime.timedelta(days=1)
        start_of_year = end_of_year - datetime.timedelta(days=2860) - datetime.timedelta(microseconds=1)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        # datestart = datetime.datetime(year=2022, month=1, day=1)
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        h = db.getHistoryDataBystart(datestart,dateend)
    else:
        s = None
        h = db.getHistoryDataByNearYear(1)
    # 单关筛选
    h = selectSingle(h,single)
    # 找出同类型数据的比赛
    someds = getSomeData(s, h, sim)
    # 胜平负 [统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏]
    spf_tjds = tjanalysisdata(someds,"spf")
    # 让球胜平负 [统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏]
    hspf_tjds = tjanalysisdata(someds,"hspf")
    # 加上被预测的比赛信息（方便界面显示）
    spf_tjds = showyuche(s,spf_tjds,"peid_spf")
    hspf_tjds = showyuche(s, hspf_tjds, "peid_hspf")

    res = {"someds":someds,"tjds":{"spf":spf_tjds,"hspf":hspf_tjds}}
    return res



if __name__ == '__main__':
    analysis(1025835,0.31)